import {ListQuery} from "@/schemas/invoke.ts";
import {invokeListQuery, invokeOperationOne} from "@/communicate/rust-invoke.ts";
import {AiConfig} from "@/schemas/ai.ts";
import {createAsyncThunk} from "@reduxjs/toolkit";
import {queryTen} from "@/common/default-some.ts";

const fetchAiConfig = async (query: ListQuery, rejectWithValue: any) => {
    const resp = await invokeListQuery<AiConfig>(
        'ai/config/list', 'ListQuery', query
    )
    if (resp.ok) return resp.data?.result || []
    return rejectWithValue('获取AI配置列表失败！')
}

export const ListAiConfig = createAsyncThunk(
    'ai/config/list',
    async (query: ListQuery, {rejectWithValue}) => await fetchAiConfig(query, rejectWithValue)
)

export const CreateAiConfig = createAsyncThunk(
    'ai/config/create',
    async (entity: AiConfig, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'ai/config/create',
            'CreateAiConfig',
            entity
        )
        if (resp.ok) return await fetchAiConfig(queryTen, rejectWithValue)
        return rejectWithValue('添加AI配置失败')
    }
)

export const UpdateAiConfig = createAsyncThunk(
    'ai/config/update',
    async (entity: AiConfig, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'ai/config/update',
            'UpdateAiConfig',
            entity
        )
        if (resp.ok) return await fetchAiConfig(queryTen, rejectWithValue)
        return rejectWithValue('添加AI配置失败')
    }
)

export const DeleteAiConfig = createAsyncThunk(
    'ai/config/delete',
    async (configId: string, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'ai/config/delete',
            'OperateAiConfig',
            {id: configId}
        )
        if (resp.ok) return await fetchAiConfig(queryTen, rejectWithValue)
        return rejectWithValue('删除AI配置失败')
    }
)

export const SetCurrentAiConfig = createAsyncThunk(
    'ai/config/set-current',
    async (configId: string, {rejectWithValue}) => {
        const resp = await invokeOperationOne(
            'ai/config/set-current',
            'OperateAiConfig',
            {id: configId}
        )
        if (resp.ok) return await fetchAiConfig(queryTen, rejectWithValue)
        return rejectWithValue('设置默认配置失败')
    }
)


